package com.xy.servicemanage.service.impl;

import com.ruoyi.common.core.domain.servicemanage.ServicesAll;
import com.ruoyi.common.core.domain.servicemanage.ServiceShow;
import com.ruoyi.common.core.domain.servicemanage.dto.ServiceQueryCondition;
import com.ruoyi.common.core.domain.servicemanage.dto.ServiceTreeNode;
import com.ruoyi.common.core.mapper.servicemanager.ServiceShowMapper;
import com.ruoyi.common.core.mapper.servicemanager.ServicesAllMapper;
import com.xy.servicemanage.service.IServiceTreeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ServiceTreeServiceImpl implements IServiceTreeService {

    @Autowired
    private ServicesAllMapper servicesAllMapper;

    @Autowired
    private ServiceShowMapper serviceShowMapper;

    // 定义特殊一级菜单的 ID（根据实际情况修改）
    private static final Long SPECIAL_FIRST_LEVEL_ID = 1L;

    @Override
    public List<ServiceTreeNode> getFullServiceTree(ServiceQueryCondition condition) {
        // 根据条件获取一级标题
        List<ServicesAll> firstLevelServices = servicesAllMapper.selectFirstLevelServicesByCondition(condition);
        System.out.println("firstLevelServices: " + firstLevelServices);
        return firstLevelServices.stream()
                .map(this::buildSubTree)
                .collect(Collectors.toList());
    }

    @Override
    public ServiceTreeNode getSubTreeByFirstLevelId(Long firstLevelId) {
        ServicesAll firstLevel = servicesAllMapper.selectByUpLevelId(firstLevelId)
                .stream()
                .findFirst()
                .orElse(null);

        if (firstLevel == null) {
            return null;
        }

        return buildSubTree(firstLevel);
    }

    private ServiceTreeNode buildSubTree(ServicesAll firstLevel) {
        ServiceTreeNode firstNode = new ServiceTreeNode(
                firstLevel.getId(),
                firstLevel.getFirstLevelTitle(),
                1
        );

        List<ServiceTreeNode> childNodes;

        // 判断是否是特殊的一级菜单
        if (SPECIAL_FIRST_LEVEL_ID.equals(firstLevel.getId())) {
            // 特殊处理：使用二级菜单的查询逻辑
            childNodes = handleSpecialFirstLevel(firstLevel);
        } else {
            // 正常处理：获取二级标题
            childNodes = handleNormalFirstLevel(firstLevel);
        }

        firstNode.setChildren(childNodes);
        return firstNode;
    }

    private List<ServiceTreeNode> handleNormalFirstLevel(ServicesAll firstLevel) {
        // 获取二级标题
        List<ServicesAll> secondLevelServices = servicesAllMapper.selectByUpLevelId(firstLevel.getId());

        return secondLevelServices.stream()
                .map(secondLevel -> {
                    ServiceTreeNode secondNode = new ServiceTreeNode(
                            secondLevel.getId(),
                            secondLevel.getSecondaryTitle(),
                            2
                    );

                    // 获取三级标题
                    List<ServiceShow> thirdLevelServices = serviceShowMapper.selectBySecondaryTitleId(secondLevel.getId());

                    List<ServiceTreeNode> thirdLevelNodes = thirdLevelServices.stream()
                            .map(thirdLevel -> {
                                ServiceTreeNode thirdNode = new ServiceTreeNode(
                                        thirdLevel.getId(),
                                        thirdLevel.getShowTitle(),
                                        3
                                );
                                thirdNode.setShowPictures(thirdLevel.getShowPictures());
                                thirdNode.setShowIntroduce(thirdLevel.getShowIntroduce());
                                thirdNode.setJumpPage(thirdLevel.getJumpPage());
                                thirdNode.setDeleted(thirdLevel.getDeleted());
                                return thirdNode;
                            })
                            .collect(Collectors.toList());

                    secondNode.setChildren(thirdLevelNodes);
                    return secondNode;
                })
                .collect(Collectors.toList());
    }

    private List<ServiceTreeNode> handleSpecialFirstLevel(ServicesAll firstLevel) {
        // 特殊一级菜单直接获取三级标题（当作二级菜单处理）
        List<ServiceShow> thirdLevelServices = serviceShowMapper.selectBySecondaryTitleId(firstLevel.getId());

        return thirdLevelServices.stream()
                .map(thirdLevel -> {
                    ServiceTreeNode thirdNode = new ServiceTreeNode(
                            thirdLevel.getId(),
                            thirdLevel.getShowTitle(),
                            2
                    );
                    thirdNode.setShowPictures(thirdLevel.getShowPictures());
                    thirdNode.setShowIntroduce(thirdLevel.getShowIntroduce());
                    thirdNode.setJumpPage(thirdLevel.getJumpPage());
                    thirdNode.setDeleted(thirdLevel.getDeleted());
                    return thirdNode;
                })
                .collect(Collectors.toList());
    }

    // 新增方法：根据条件过滤服务树
    public List<ServiceTreeNode> getFilteredServiceTree(ServiceQueryCondition condition) {
        List<ServiceTreeNode> fullTree = getFullServiceTree(condition);
        return fullTree.stream()
                .map(node -> filterNode(node, condition))
                .filter(node -> node != null && (node.getChildren() != null && !node.getChildren().isEmpty()))
                .collect(Collectors.toList());
    }

    private ServiceTreeNode filterNode(ServiceTreeNode node, ServiceQueryCondition condition) {
        if (condition.getFirstLevelTitle() != null && !node.getFirstLevelTitle().contains(condition.getFirstLevelTitle())) {
            return null;
        }


        if (condition.getDeleted() != null && node.getDeleted() != condition.getDeleted()) {
            return null;
        }

        if (node.getChildren() != null) {
            List<ServiceTreeNode> filteredChildren = node.getChildren().stream()
                    .map(child -> filterNode(child, condition))
                    .filter(child -> child != null)
                    .collect(Collectors.toList());
            node.setChildren(filteredChildren);
        }

        return node;
    }
}